
#include "video/MovableObject.h"
#include "video/SceneNode.h"
#include "video/Camera.h"
#include "video/RaySceneQuery.h"
#include "video/RenderQueue.h"

#include "video/NameGenerator.h"

namespace KEngine
{

MovableObject::MovableObject()
: mParentNode(NULL)
, mName("")
, mVisible(true)
, mRenderQueueID(RENDER_QUEUE_MAIN)
{
	mName = NameGenerator::getSingleton().generateMovableObjectName();
};

MovableObject::~MovableObject()
{

}

void MovableObject::update()
{

}

void MovableObject::render(Camera* camera, TimeValue t)
{

}

void MovableObject::setName(const std::string& name)
{
	mName = name;
}

const std::string& MovableObject::getName()
{
	return mName;
}

void MovableObject::setAttached(SceneNode* parent)
{
	mParentNode = parent;
}

bool MovableObject::isAttached()
{
	return mParentNode != NULL;
}

const AxisAlignedBox& MovableObject::getWorldBoundingBox(bool derive /* = false */)
{
	if (derive)
	{
		mWorldAABB = getBoundingBox();
		D3DXMATRIX mat;
		getParentNodeTransform(mat);
		mWorldAABB.transformAffine(mat);
	}

	return mWorldAABB;
}

const AxisAlignedBox& MovableObject::getBoundingBox()
{
	return mWorldAABB;
}

SceneNode* MovableObject::getParentNode()
{
	return mParentNode;
}

void MovableObject::getParentNodeTransform(D3DXMATRIX& mat)
{
	if (mParentNode)
		mat = mParentNode->getCachedTransform();
	else
		D3DXMatrixIdentity(&mat);
}

void MovableObject::setVisible(bool visible)
{
	mVisible = visible;
}

bool MovableObject::isVisible() const
{
	return mVisible;
}

void MovableObject::setRenderQueueGroup(unsigned int queueID)
{
	mRenderQueueID = queueID;
}

unsigned int MovableObject::getRenderQueueGroup() const
{
	return mRenderQueueID;
}

void MovableObject::intersects(RaySceneQuery& raySceneQuery)
{
	if (!isVisible())
		return;

	std::pair<bool, float> result = raySceneQuery.getRay().intersects(getWorldBoundingBox(true));
	if (result.first)
		raySceneQuery.queryResult(this, result.second);
}

}